package com.code.translate.plugins;

import com.alibaba.fastjson.JSON;
import com.code.translate.function.DocumentTranslatePlugin;
import com.code.translate.utils.CookieUtils;
import com.code.translate.utils.HttpUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.Cookie;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author ggh
 * @date 2022/10/14
 * <p>
 * Deepl翻译(废弃,免费试用次数太少)
 */
@Deprecated
public class DeeplTranslatePlugin extends DocumentTranslatePlugin {
    private final static String indexUrl = "https://www.deepl.com/translator";
    private final static String translateUrl = "https://www2.deepl.com/jsonrpc?method=LMT_handle_jobs";
    private final static String referUrl = "https://www.deepl.com/";

    // 文本翻译
    private final static String imageIndexUrl = "https://www.deepl.com/translator/files";
    private final static String tokenUrl = "https://clearance.deepl.com/token";
    private final static String cssUrl = "https://static.deepl.com/css/deepl.$8a363f.css";
    private final static String webUrl = "https://w.deepl.com/web?request_type=jsonrpc&il=ZH&method=getClientState";
    private final static String phpUrl = "https://www.deepl.com/PHP/backend/privacy.php?request_type=jsonrpc&il=ZH&method=setPrivacySettings";

    private final static String uploadFileUrl = "https://backend.deepl.com/documentTranslation/upload?fileExtension=docx&expectsPro=false";

    private final static String staticUrl = "https://s.deepl.com/web/statistics";
    private final static String downloadFileUrl = "https://backend.deepl.com/documentTranslation/download";

    private final static Integer signleTranslateTextLen = 5000;

    @Override
    protected Map<String, Object> prepareDocuemnt() throws Exception {
        return null;
    }

    @Override
    public String doTranslateDocumentByStream(InputStream inputStream, Map<String, Object> params) throws Exception {
        RequestEntity imageIndexRequest = RequestEntity.get(URI.create(imageIndexUrl)).build();
        ResponseEntity imageIndexResponse = HttpUtils.reqEntity(imageIndexRequest);
        Map<String, Cookie> map = CookieUtils.parseResponseCookie(imageIndexResponse.getHeaders().get("set-cookie"));

        Map<String, Object> innerparamss = new HashMap<>();
        innerparamss.put("clientVars", null);
        innerparamss.put("v", "20180814");

        Map<String, Object> paramss = new HashMap<>();
        paramss.put("jsonrpc", "2.0");
        paramss.put("id", 18150022);
        paramss.put("params", innerparamss);
        paramss.put("method", "getClientState");
        System.out.println(JSON.toJSONString(paramss));
        RequestEntity webRequest = RequestEntity.post(URI.create(webUrl)).header("content-type", "application/json").body(paramss);
        ResponseEntity webResponse = HttpUtils.reqEntity(webRequest);

        RequestEntity cssRequest = RequestEntity.get(URI.create(cssUrl)).build();
        ResponseEntity cssResponse = HttpUtils.reqEntity(cssRequest);
        Map<String, Cookie> cssmap = CookieUtils.parseResponseCookie(cssResponse.getHeaders().get("set-cookie"));

        Map<String, Object> phpinnerparamss = new HashMap<>();
        phpinnerparamss.put("consent", Arrays.asList("NECESSARY", "PERFORMANCE", "COMFORT"));
        phpinnerparamss.put("mode", "LAX_AUTO");

        paramss = new HashMap<>();
        paramss.put("jsonrpc", "2.0");
        paramss.put("id", 18150022);
        paramss.put("params", phpinnerparamss);
        paramss.put("method", "setPrivacySettings");
        System.out.println(JSON.toJSONString(paramss));

        RequestEntity phpRequest = RequestEntity.post(URI.create(phpUrl)).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(paramss);
        ResponseEntity phpResponse = HttpUtils.reqEntity(phpRequest);
        Map<String, Cookie> phpmap = CookieUtils.parseResponseCookie(phpResponse.getHeaders().get("set-cookie"));
        System.out.println(JSON.toJSONString(phpmap));

        Double d = Math.floor(System.currentTimeMillis() / 1000);
        Integer ii = d.intValue();
        String s = "{\"sid\":\"" + UUID.randomUUID().toString() + "\",\"lastUpdate\":" + ii + "}";
        System.out.println(s);
        String dapSidStr = URLEncoder.encode(s);
        System.out.println(dapSidStr);


        String precookie = CookieUtils.buildCookie(map.get("dapUid"), cssmap.get("__cf_bm"), phpmap.get("privacySettings"));
        precookie = precookie + ";dapSid=" + dapSidStr + ";dapVn=1";
        System.out.println(precookie);

        RequestEntity tokenRequest = RequestEntity.get(URI.create(tokenUrl)).header("cookie", precookie).build();
        ResponseEntity tokenResponse = HttpUtils.reqEntity(tokenRequest);
        System.out.println(JSON.toJSONString(tokenResponse.getHeaders().get("set-cookie")));
        Map<String, Cookie> map2 = CookieUtils.parseResponseCookie(tokenResponse.getHeaders().get("set-cookie"));
        System.out.println(tokenResponse.getBody());
        System.out.println(JSON.toJSONString(map2));

        String cookie = CookieUtils.buildCookie(map2.get("dl_clearance"));
        System.out.println(cookie);

//
//        Map<String, Object> requestParams = new HashMap<>(1);
//        requestParams.put("file", inputStream);
//        requestParams.put(Constants.FILE_CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//
//        Map<String, String> requestHeads = new HashMap<>(3);
//        requestHeads.put("referer", referUrl);
//        requestHeads.put("origin", "https://www.deepl.com");
////        requestHeads.put("cookie", cookie);
//        requestHeads.put("cookie", "dl_clearance=v2PfHYDl1jXm-4EmAOE8GW1e-ZFrvQ5_Rv3b_cKQY5SAVt_mtErl3mzp8kysMAiKs_Q0OhzXeTspX6fk_ynnRtILu209jsKvpHgfb4_0TthTjw");
//        requestHeads.put(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
//        String result = HttpUtils.req(uploadFileUrl, HttpMethod.POST, requestHeads, requestParams);
//        System.out.println(result);
        return null;
    }

    @Override
    protected Map<String, Object> prepare() {
        return null;
    }

    @Override
    protected String doTranslate(String text, Map<String, Object> params) throws Exception {
        return null;
    }

    private static Map<String, Object> structParams(String text, Map<String, Object> needParams) throws Exception {
        Map<String, Object> outerParams = new HashMap<>(9);

        outerParams.put("jsonrpc", "2.0");
        outerParams.put("method", "LMT_handle_jobs");

        Map<String, Object> innerParams = new HashMap<>(9);

        Map<String, Object> commonJobParams = new HashMap<>(3);
        commonJobParams.put("browserType", 1);
        commonJobParams.put("formality", null);
        commonJobParams.put("mode", "translate");

        Map<String, Object> weightParams = new HashMap<>(1);
        weightParams.put("EN", 0.5);
        Map<String, Object> preferenceParams = new HashMap<>(1);
        preferenceParams.put("weight", weightParams);
        preferenceParams.put("default", "default");
        Map<String, Object> langParams = new HashMap<>(1);
        langParams.put("preference", preferenceParams);
        langParams.put("source_lang_user_selected", "EN");
        langParams.put("target_lang", "ZH");


        List<Sentence> sentences = Arrays.asList(new Sentence("book", 0, ""));
        innerParams.put("jobs", Arrays.asList(new JobData("default", 4, null, null, "fast", sentences)));

        innerParams.put("lang", langParams);
        innerParams.put("priority", 1);
        innerParams.put("commonJobParams", commonJobParams);

        outerParams.put("params", innerParams);
        outerParams.put("id", 29100013);

        return outerParams;
    }

    static class JobData {
        private String kind;
        private Integer preferred_num_beams;
        private String[] raw_en_context_before;
        private String[] raw_en_context_after;
        private String quality;
        private List<Sentence> sentences;

        public JobData(String kind, Integer preferred_num_beams, String[] raw_en_context_before, String[] raw_en_context_after, String quality, List<Sentence> sentences) {
            this.kind = kind;
            this.preferred_num_beams = preferred_num_beams;
            this.raw_en_context_before = raw_en_context_before;
            this.raw_en_context_after = raw_en_context_after;
            this.quality = quality;
            this.sentences = sentences;
        }

        public String getKind() {
            return kind;
        }

        public Integer getPreferred_num_beams() {
            return preferred_num_beams;
        }

        public String[] getRaw_en_context_before() {
            return raw_en_context_before;
        }

        public String[] getRaw_en_context_after() {
            return raw_en_context_after;
        }

        public List<Sentence> getSentences() {
            return sentences;
        }
    }

    static class Sentence {
        private String text;
        private Integer id;
        private String prefix;

        public Sentence(String text, Integer id, String prefix) {
            this.text = text;
            this.id = id;
            this.prefix = prefix;
        }

        public String getText() {
            return text;
        }

        public Integer getId() {
            return id;
        }

        public String getPrefix() {
            return prefix;
        }
    }

    static class Lang {
        private Preference preference;
        private String source_lang_user_selected;
        private String target_lang;
    }

    static class Preference {
        private Weight weight;
    }

    static class Weight {
        private String EN;
    }
}
